<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
    <style>
        .aui-searchbar-input {
            width: 98% !important;
        }
    </style>
</head>

<body>
    <header id='header' class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;">
        <a class="aui-pull-left aui-btn" onclick="api.closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="middle" style="font-size: 0.8rem;">
            <span>TID盘点</span><span id="titleVal"></span>
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:60px;">
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">操作状态 </div>
                    <div class="aui-list-item-input">
                        <label><input class="aui-radio" type="radio" value="OnLine" name="lineType" checked> 在线</label>
                        <label><input class="aui-radio" type="radio" value="OffLine" name="lineType"> 离线</label>
                    </div>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">计划日期</div>
                    <div class="aui-list-item-input" onclick="timePicker();">
                        <input type="text" placeholder="选择日期" class="aui-input" id="update">
                        <!-- <input readonly class="form-control" type="text" id="update" placeholder="请选择"> -->
                    </div>
                </div>
            </li>

            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">仓库</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="选择/扫描 仓库" id="workCenterCode" value=""
                            onclick="getIdSelector();" />
                    </div>
                    <i id="centerSelect" class="aui-input-addon aui-iconfont aui-icon-right"
                        onclick="goSelectWorkCenter()"></i>
                </div>
            </li>

            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">器具条码</div>
                    <div class="aui-list-item-input">
                        <input type="text" placeholder="" id="codeBar" value="" disabled="true"
                            onclick="getIdSelector();" />
                    </div>
                    <div class="aui-btn aui-btn-primary" style="margin-right: 0.5rem;background-color: #03a9f4"
                        onclick="doSearch()">寻卡</div>
                </div>
            </li>

            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">器具数量</div>
                    <div class="aui-list-item-input">
                        <input disabled=true type="text"  id="number" value="" onclick="getIdSelector();" />
                    </div>
                  
                </div>
            </li>
        </ul>

    </div>

    <div style="width:100%;margin-top:2%;"></div>
    <div class="aui-btn aui-btn-info" style="width:90%;margin-left:5%;" onclick="determineSave()">盘点确认</div>
    <!-- <div class="aui-btn aui-btn-info" style="margin-left:8%;width:40%;;" onclick="deleteData()">离线保存</div> -->

    <div style="background-color:white; height: 100%;width: 100%;margin-top:2%;margin-bottom:50px;">
        <table class="table" style='width:100%;' id="table">
            <thead>
                <tr
                    style="text-align: center;background-color: #DCE9F2;color: #467aa7;font-size: 12px;font-weight: bold;word-wrap:break-word;word-break:break-all;">
                    <td algin='center' width='80%'>器具条码</td>
                    <td algin='center' width='20%'>操作</td>
                </tr>
            </thead>
            <tbody id="tbodyHtml">
            </tbody>
        </table>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/jdate.min.js"></script>
<script type="text/javascript">
    var listData;
    var idSelector = "";//光标所在id
    var scanRule = ""; //条码解析规则

    var workCellGid = "";
    var workCellCode = "";
    var workCellName = "";

    var workCenterGid = ""; //仓库GID
    var workCenterCode = ""; //仓库编码
    var workCenterName = ""; //仓库名称
    var arraylist = new Array();

    //初始化查询仓库下拉框
    apiready = function () {
        $("#codeBar").focus();
        idSelector = "codeBar";
        listData = [];

        // new Jdate({
        //     el: '#update',
        //     format: 'YYYY-MM-DD hh:mm:ss',
        //     beginYear: 2000,
        //     endYear: 2100
        // });

    }


    //2：选中仓库
    function goSelectWorkCenter() {
        api.openWin({
            name: 'uwmSelectWorkCenter',
            url: 'uwmSelectWorkCenter.html',
            pageParam: {
                flag: "in",
                name: "uwmInventoryTask_tid",
                mrlCode: "",
                lotCode: "",
                qty: ""
            }
        });
    }


    //仓库选择后回调函数
    function setWorkCenter(id, code, name) {
        workCenterGid = id;
        workCenterCode = code;
        workCenterName = name;
        //$("#workCenterCode").attr("value",code+":"+name);
        document.getElementById('workCenterCode').value = code + ":" + name;
    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //扫描
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {
            if (idSelector == 'cellCode') {

                $("#cellCode").val(ret);
                getWorkCell(ret, "cellCode");
            } else if (idSelector == 'codeBar') {

                tmSplit(ret);

            }
        });
    }

    //3；PDA自带扫描回车事件
    $("#codeBar").on('keypress', function (e) { //#keyword为input文本框
        var keycode = e.keyCode;
        var sm = $(this).val();
        if (keycode == '13') {
            //仓库编码
            if (sm != null && sm != "" && sm != undefined) {
                $("#codeBar").blur();

                var codeBarCells = document.querySelectorAll("td[name='codeBar']");
                var codeBarArray = [];
                // 遍历这些<td>元素并提取它们的文本值
                codeBarCells.forEach(function (cell) {
                    codeBarArray.push(cell.innerText.trim());
                });

                if (!codeBarArray.includes(sm)) {
                    var html = "";
                    html += "<tr style='text-align: center;color: black;font-size: 12px;background-color: #F5F5F5;'>";
                    html += "<td name='codeBar'>" + sm + "</td>";
                    html += "<td name='button'>" + "<div class='aui-btn aui-btn-info' onclick=\"deleteRow(this,'" + sm + "')\">删除</div> " + "</td>";
                    html += "</tr>";
                    $("#tbodyHtml").append(html);
                }
                $("#codeBar").val("");
                $("#codeBar").focus();
                //$api.html($api.byId("tbodyHtml"), html);
            }
        }
    });

    function deleteRow(button,tid) {
        $("#number").val($("#number").val()-1);
        var row = button.parentNode.parentNode;
        // 获取表格的引用
        var table = document.getElementById("table").getElementsByTagName('tbody')[0];
        arraylist = arraylist.filter(item => item.TID !== tid);
        // 删除当前行
        table.removeChild(row);
    }

    function determineSave() {
        //操作状态
        var lineType = $("input[name='lineType']:checked").val();

        var update = $("#update").val();



        if (update == undefined || update == null || update == '') {
            api.toast({
                msg: '请选择日期',
                duration: 3000
            });
            return;
        }


        if (lineType == 'OnLine') {
            console.log('1')
            if (workCenterCode == undefined || workCenterCode == null || workCenterCode == '') {
                api.toast({
                    msg: '请选择仓库',
                    duration: 3000
                });
                return;
            }
            save();
        } else if (lineType == 'OffLine') {
            console.log('2')
            sqliteSave(update);
        }
    }

    function save() {


        var codeBarCells = document.querySelectorAll("td[name='codeBar']");
        var codeBarArray = [];
        // 遍历这些<td>元素并提取它们的文本值
        codeBarCells.forEach(function (cell) {
            codeBarArray.push(cell.innerText.trim());
        });
        // 将提取的值合并成一个字符串
        var codeBar = codeBarArray.join(",");

        var update = $("#update").val();

        if (update == undefined || update == null || update == '') {
            api.toast({
                msg: '请选择日期',
                duration: 3000
            });
            return;
        }
        api.showProgress({
            title: '保存中...',
        });

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/tidUpload";
        var data = {
            values: {
                un: un,
                appVersion: api.appVersion,
                date: update,
                codeBar: codeBar,
                workCenterCode: workCenterCode
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {

                    api.hideProgress();
                    api.toast({
                        msg: "保存成功",
                        duration: 3000
                    });
                    arraylist=new Array();
                    $api.html($api.byId("tbodyHtml"), "");
                    $("#number").val("0");
                } else if (myobj.code == '1') {
                    $("#codeBar").val("");
                    api.hideProgress();
                    $("#codeBar").select();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });

        api.hideProgress();
    }

    //离线盘点
    function sqliteSave(date) {

        var db = api.require('db');
        db.openDatabase({
            name: 'test'
        }, function (ret, err) {
            if (ret.status) {
                console.log("1：数据库创建成功");

                //创建数据表
                db.executeSql({
                    name: 'test',
                    sql: 'CREATE TABLE if not exists tidcoding( tdate blob, code varchar(255))'
                }, function (ret, err) {
                    if (ret.status) {

                        console.log("2：数据库表tidcoding创建成功");

                        var codeBarCells = document.querySelectorAll("td[name='codeBar']");
                        var codeBarArray = [];
                        // 遍历这些<td>元素并提取它们的文本值
                        codeBarCells.forEach(function (cell) {

                            //插入数据
                            db.executeSql({
                                name: 'test',

                                sql: " insert into tidcoding(tdate,code) values(datetime('" + date + "'),'" + cell.innerText.trim() + "')"

                            }, function (ret, err) {
                                if (ret.status) {
                                    api.hideProgress();
                                    api.toast({
                                        msg: "数据已存至本地数据库",
                                        duration: 3000
                                    });
                                    console.log("3：数据库表数据插入成功");
                                    $api.html($api.byId("tbodyHtml"), "");
                                    $("#number").val("0");
                                    arraylist=new Array();
                                }
                                //  else {
                                //     alert(JSON.stringify(err));
                                // }
                            });
                        });


                    } else {
                        alert(JSON.stringify(err));
                    }
                });

                var html = "";
                $("#tbodyHtml").append(html);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    //调用RFID扫码api
    function doSearch() {
        // alert('ret');
        var moduleUhfRfid = api.require('moduleUhfRfid');
        moduleUhfRfid.startActivityForResult({
            appParam: ""
        }, function (ret, err) {
            // alert('1234');
            if (ret) {

                var array = eval(ret);
                arraylist = arraylist.concat(array);

                // 或者使用filter和findIndex  
                var list = arraylist.filter((only, index, self) =>  
                index === self.findIndex((t) => (  
                    t.TID === only.TID  
                ))
                );
                $("#number").val(list.length);
                var html = "";
                if (list != null && list != undefined && list.length > 0) {
                    document.getElementById('tbodyHtml').innerHTML = '';
                    //divStr += "<tr style='text-align:center;color:#0099FF;border-collapse: collapse'><th style='border: 1px solid white;border-collapse: collapsel;width:60%'>器具条码</th><th style='border: 1px solid white;border-collapse: collapse;width:40%'>删除条码</th></tr>"
                    for (var i = 0; i < list.length; i++) {
                        //divStr += "<tr style='text-align:center;color:#0099FF;border-collapse: collapse'><td id= 'tm' style='border: 1px solid white;border-collapse: collapse;width:60%''>" + list[i].ASCII + "</td>" + "<td style='border: 1px solid white;border-collapse: collapse;width:40%'><button class='deleteRowBtn' style = 'border:none:outline:none;background-color:red'>删除</button></td></tr>"

                        html += "<tr style='text-align: center;color: black;font-size: 12px;background-color: #F5F5F5;'>";
                        html += "<td name='codeBar'>" + list[i].TID + "</td>";
                        html += "<td name='button'>" + "<div class='aui-btn aui-btn-info' onclick=\"deleteRow(this,'" + list[i].TID + "')\">删除</div> " + "</td>";
                        html += "</tr>";
                    }
                    // $("$table").append(divStr);
                    $("#tbodyHtml").append(html);
                }

                $("#codeBar").val("");
                $("#codeBar").focus();
            } else {
                //alert(err);
            }
        });
    }

    //时间选择器
    function timePicker(id) {
        api.openPicker({
            type: 'date',
            date: new Date(),
            title: '选择日期'
        }, function (ret, err) {
            if (ret) {
                var monthTemp = (ret.month < 10 ? '0' + ret.month : ret.month);
                var dayTemp = (ret.day < 10 ? '0' + ret.day : ret.day);
                var date = ret.year + "-" + monthTemp + "-" + dayTemp;
                $("#update").val(date);
            }
        });
    }
    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>